package com.jintoufs.service.role.impl;

import com.jintoufs.dao.role.RoleDAO;
import com.jintoufs.domain.role.Role;
import com.jintoufs.service.role.RoleService;
import com.jintoufs.service.security.AuthorizationService;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.util.ztree.TreeNode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(value = "roleService")
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleDAO roleDAO;

    @Resource
    private AuthorizationService authorizationService;

    @Override
    public Map<String, Object> add(Role entity, String resourceIds) {
        Map<String, Object> result = new HashMap<>();
        roleDAO.insert(entity);
        Integer id = entity.getId();
        if (id==null||id == 0) {
            result.put("status", "ERROR");
            result.put("msg", "新增失败");
        } else {
            authorizationService.grant(id, resourceIds);
            result.put("status", "OK");
            result.put("msg", "新增成功");
        }
        return result;
    }

    @Override
    public Map<String, Object> update(Role entity, String resourceIds) {
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = roleDAO.update(entity);
        if (flag) {
            authorizationService.grant(entity.getId(), resourceIds);
            result.put("status", "OK");
            result.put("msg", "编辑成功");
        } else {
            result.put("status", "ERROR");
            result.put("msg", "编辑失败");
        }
        return result;
    }

    @Override
    public void delete(Integer id) {
        roleDAO.delete(id);
    }

    @Override
    public List<Role> getByFilter(Map<String, Object> params) {
        return roleDAO.getByFilter(params);
    }

    @Override
    public List<TreeNode> getRoleMenu(String roleId) {
        Map<String, Object> params = new HashMap<String, Object>();
        List<Role> list = roleDAO.getByFilter(params);
        List<TreeNode> nodes = new ArrayList<TreeNode>();
        /* 根据网点OID构建数据时,只需要两级即可(网点及其直接上级区域) */
        for (Role tmp : list) {
            TreeNode areaNode = new TreeNode();
            areaNode.setId(String.valueOf(tmp.getId()));
            areaNode.setName(tmp.getRoleName());
            if (!"".equals(roleId) && Integer.parseInt(roleId) == tmp.getId()) {
                areaNode.setChecked(true);
            }
            nodes.add(areaNode);
        }
        return nodes;
    }
}
